package org.cqupt.content.counter.service.imp;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.cqupt.content.counter.domain.Article;
import org.cqupt.content.counter.domain.ArticleExample;
import org.cqupt.content.counter.entity.ArticleEntity;
import org.cqupt.content.counter.entity.ArticleList;
import org.cqupt.content.counter.persistence.ArticleMapper;
import org.cqupt.content.counter.service.ArticleService;
import org.cqupt.content.counter.utils.ArticleContent;
import org.cqupt.content.counter.utils.CountWord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * ArticleService实现类
 * @author TomWang
 *
 */
@Service
@Transactional
public class ArticleServiceImp implements ArticleService {
	//注入持久化层
	@Autowired
	ArticleMapper ArticleMapper;

	@Override
	public ArticleList insertOrUpdate(ArticleEntity arEntity,int page) throws IOException {
		//获取文章内容
		ArticleContent.getArticle(arEntity);
		ArticleExample example = new ArticleExample();
		example.createCriteria().andTitleEqualTo(arEntity.getTitle());
		List<Article> articles = ArticleMapper.selectByExample(example);
		//统计字数
		CountWord.count(arEntity);
		Article article = null;
		if (articles.size() == 1) {
			article = articles.get(0);
			article.setChinese_word(arEntity.getChineseWord());
			article.setEnglish_word(arEntity.getEnglishWord());
			article.setMarks_count(arEntity.getMarksCount());
			article.setWord_count(arEntity.getWordCount());
			article.setCreate_time(new Date());
			ArticleMapper.updateByPrimaryKey(article);
		} else if (articles.size() == 0) {
			article = new Article();
			article.setTitle(arEntity.getTitle());
			article.setChinese_word(arEntity.getChineseWord());
			article.setEnglish_word(arEntity.getEnglishWord());
			article.setMarks_count(arEntity.getMarksCount());
			article.setWord_count(arEntity.getWordCount());
			article.setCreate_time(new Date());
			ArticleMapper.insert(article);
		} else {
			throw new RuntimeException("数据库中存在异常标题重复数据");
		}
		return get(0,page);

	}

	@Override
	public int delete(int articleId) {
		return ArticleMapper.deleteByPrimaryKey(articleId);
	}

	@Override
	public ArticleList get(int index, int page) {
		ArticleList aList = new ArticleList();
		//查询页数
		RowBounds rowBounds = new RowBounds(index, page);
		ArticleExample articleExample = new ArticleExample();
		articleExample.setOrderByClause("create_time desc");
		List<Article> articleList = ArticleMapper.selectByExampleWithRowbounds(articleExample, rowBounds);
		aList.setArticleList(articleList);
		//查询总条数
		int total = ArticleMapper.countByExample(articleExample);
		aList.setTotal(total);
		return aList;
	}
}
